package com.atguigu.spzx.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.feign.order.OrderFeignClient;
import com.atguigu.spzx.feign.product.ProductFeignClient;
import com.atguigu.spzx.model.dto.product.SkuSaleDto;
import com.atguigu.spzx.model.entity.order.OrderInfo;
import com.atguigu.spzx.model.entity.order.OrderItem;
import com.atguigu.spzx.model.entity.pay.PaymentInfo;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.pay.mapper.PaymentInfoMapper;
import com.atguigu.spzx.pay.service.PaymentInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PaymentInfoServiceImpl implements PaymentInfoService {

    @Autowired
    OrderFeignClient orderFeignClient;

    @Autowired
    PaymentInfoMapper paymentInfoMapper;

    @Autowired
    ProductFeignClient productFeignClient;


    @Override
    public PaymentInfo savePaymentInfo(String orderNo) {

        OrderInfo orderInfo = orderFeignClient.getOrderInfoByOrderNo(orderNo).getData();

        PaymentInfo paymentInfo = paymentInfoMapper.getByOrderNo(orderNo);

        if(paymentInfo == null){   //首次提交  “确认支付” 需要保存支付信息，再去调用支付宝进行支付。  如果，首次提交后并没有支付，但已保存过支付信息了，那么，再次支付时，无需再保存支付信息。
            paymentInfo = new PaymentInfo();

            paymentInfo.setUserId(orderInfo.getUserId());
            paymentInfo.setPayType(2); // 正常情况下，用户选择支付类型。
            String content = "";
            for(OrderItem item : orderInfo.getOrderItemList()) {
                content += item.getSkuName() + " ";
            }
            paymentInfo.setContent(content);
            paymentInfo.setAmount(orderInfo.getTotalAmount());
            paymentInfo.setOrderNo(orderNo);
            paymentInfo.setPaymentStatus(0);
            paymentInfoMapper.save(paymentInfo);
        }

        return paymentInfo;
    }

    @Override
    public void updatePaymentStatus(Map<String, String> map, int payType) {
        log.info("支付宝扣款后异步回调返回的数据："+map);

        //1.更新支付信息  payment_info
        // 查询PaymentInfo
        PaymentInfo paymentInfo = paymentInfoMapper.getByOrderNo(map.get("out_trade_no"));  //out_trade_no 支付宝把订单编号又返回给咱们
        if (paymentInfo.getPaymentStatus() == 1) { //异步通知可能出现重复通知 8次  所以业务逻辑执行过后，重复调用时不再执行，直接return.
            return;
        }

        //更新支付信息
        paymentInfo.setPaymentStatus(1);
        paymentInfo.setOutTradeNo(map.get("trade_no"));  //trade_no  支付宝扣款生成交易流水号。
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(JSON.toJSONString(map));
        paymentInfo.setPayType(payType);
        paymentInfoMapper.updateById(paymentInfo);


        //2.更新订单状态信息    order_info    同时保持日志   order_log
        orderFeignClient.updateOrderStatus(map.get("out_trade_no"),payType);

        //3.更新商品库存和销量   product_sku
        OrderInfo orderInfo = orderFeignClient.getOrderInfoByOrderNo(paymentInfo.getOrderNo()).getData();
        List<SkuSaleDto> skuSaleDtoList = orderInfo.getOrderItemList().stream().map(item -> {
            SkuSaleDto skuSaleDto = new SkuSaleDto();
            skuSaleDto.setSkuId(item.getSkuId());
            skuSaleDto.setNum(item.getSkuNum());
            return skuSaleDto;
        }).collect(Collectors.toList());
        productFeignClient.updateSkuSaleNum(skuSaleDtoList);
    }
}
